<?php
/**
 * 合伙人相关类
 * @see以下说的“团队销售总额”均不包含 他本人的销售额
 * @author 志杨
 *
 */
class Tarento
{
	var $db;
	var $tpl;
	var $config;
	var $page;
	var $selectSql;
	var $extra_rate = 0.03;//合伙人额外返利比例
	
	function Tarento()
	{
		global $db;
		
		global $tpl;
		
		global $config;
		
		$this -> db     = & $db;
		$this -> tpl    = & $tpl;
		$this -> config    = $config;
	}
	
	/**
	 * 获取某用户下一级合伙人信息
	 * @param int $memberId 默认取顶级合伙人信息
	 * @param boolean $isSelf 是否只查当前用户（用户ID大于0有效）
	 */
	function get_tarento_list($memberId=0,$isSelf=FALSE){
		$res = array();
		$sql = "";
		if($memberId==0){//查顶级合伙人列表
			$sql = "select a.*,b.name,b.qq,b.weixin,b.mobile from ".TARENTO." AS a left join ".MEMBER." AS b ON a.member_id=b.userid where a.level=1 and a.relations!=''";
		}elseif ($memberId>0){
			if($isSelf){//只查当前传入用户信息
				$sql = "select a.*,b.name,b.qq,b.weixin,b.mobile from ".TARENTO." AS a left join ".MEMBER." AS b ON a.member_id=b.userid where a.member_id={$memberId}";
			}else{//查当前传入用户直系下一级合伙人列表
				//先通过当前用户信息得到下一级查询条件
				$sqlTemp = "select relations,level from ".TARENTO." where member_id={$memberId}";
				$this->db->query($sqlTemp);
				$memberInfo = $this->db->fetchRow();
				if(!empty($memberInfo)){
					$condStr = " relations like '".$memberInfo['relations']."_%' and level=".($memberInfo['level']+1);
					$sql = "select a.*,b.name,b.qq,b.weixin,b.mobile from ".TARENTO." AS a left join ".MEMBER." AS b ON a.member_id=b.userid where {$condStr}";
				}
			}
		}
		if(!empty($sql)){
			$this->db->query($sql);
			$res = $this->db->getRows();
		}
		
		return $res;
	}
	
	/**
	 * 获取合伙人结算信息（自己或直属下一级）
	 * @param number $memberId 默认取顶级合伙人信息
	 * @param string $monthStr 月份，如201509
	 * @param string $isSelf 是否只查当前用户（用户ID大于0有效）
	 */
	public function get_tarento_settlement_records($memberId=0,$monthStr='',$isSelf=FALSE){
		$res = array();
		$sql = "";
		$str = "";
		if($monthStr){
			$str = "and a.flow_time_str='".$monthStr."'";
		}
		if($memberId==0){//查顶级合伙人列表
			$sql = "select a.*,b.name from ".TARENTOSALESFLOW." as a left join ".MEMBER." as b on a.member_id=b.userid where a.relations!='' and a.level=1 {$str} ";
		} elseif ($memberId>0){
			if($isSelf){//只查当前传入用户信息
				$sql = "select a.*,b.name from ".TARENTOSALESFLOW." as a left join ".MEMBER." as b on a.member_id=b.userid where a.relations!='' and a.member_id={$memberId} {$str} ";
			} else {//查当前传入用户直系下一级合伙人列表
				//先通过当前用户信息得到下一级查询条件
				$sqlTemp = "select relations,level from ".TARENTOSALESFLOW." a where member_id={$memberId} {$str}";
				$this->db->query($sqlTemp);
				$memberInfo = $this->db->fetchRow();
				if(!empty($memberInfo)){
					$condStr = " a.relations like '".$memberInfo['relations']."_%' and a.level=".($memberInfo['level']+1);
					$sql = "select a.*,b.name from ".TARENTOSALESFLOW." as a left join ".MEMBER." as b on a.member_id=b.userid where {$condStr} {$str}";
				}
			}
		}
		if(!empty($sql)){
			$this->db->query($sql);
			$res = $this->db->getRows();
		}
		
		return $res;
	}
	
	/**
	 * 获取合伙人团队总人数（包含他自己）
	 * @param unknown $memberId
	 */
	function get_tarento_group_total_num($memberId){
		$num = 1;
		if($memberId>0){
			$sqlTemp = "select relations,level from ".TARENTO." where member_id={$memberId}";
			$this->db->query($sqlTemp);
			$memberInfo = $this->db->fetchRow();
			if(!empty($memberInfo) && $memberInfo['relations']!=''){
				$sql = "select count(*) as num from ".TARENTO." where relations like '".$memberInfo['relations']."_%' ";
				$this->db->query($sql);
				$num += $this->db->fetchField('num');
			}
		}
		
		return $num;
	}
	
	/**
	 * 获取合伙人团队某月需要结算总人数（包含他自己）
	 * @param unknown $memberId
	 * @param string $monthStr
	 * @return Ambigous <number, NULL>
	 */
	function get_tarento_group_month_settlement_num($memberId,$monthStr){
		$num = 1;
		if($memberId>0 && !empty($monthStr)){
			$sqlTemp = "select relations,level from ".TARENTOSALESFLOW." where member_id={$memberId} and flow_time_str='{$monthStr}'";
			$this->db->query($sqlTemp);
			$memberInfo = $this->db->fetchRow();
			if(!empty($memberInfo) && $memberInfo['relations']!=''){
				$sql = "select count(*) as num from ".TARENTOSALESFLOW." where relations like '".$memberInfo['relations']."_%' and flow_time_str='{$monthStr}'";
				$this->db->query($sql);
				$num += $this->db->fetchField('num');
			}
		}
	
		return $num;
	}
	
	/**
	 * 获取合伙人及他的团队本月销售额
	 * @param unknown $memberId
	 * @param unknown $monthStr 如201509
	 */
	function get_tarento_current_month_sales($memberId,$monthStr=''){
		$selfSales = 0;
		$teamSales = 0;
		if(empty($monthStr)){
			$monthStr = date('Ym');
		}
		$sql = "select self_sales,relations from ".TARENTOSALESFLOW." where member_id={$memberId} and flow_time_str='{$monthStr}'";
		$this->db->query($sql);
		$memberInfo = $this->db->fetchRow();
		$selfSales = $memberInfo['self_sales']?$memberInfo['self_sales']:0;
		if(empty($memberInfo)){
			$sql = "select relations from ".TARENTO." where member_id={$memberId}";
			$this->db->query($sql);
			$memberInfo = $this->db->fetchRow();
		}
		if($memberInfo['relations']!=''){
			$sql = "select sum(self_sales) as total from ".TARENTOSALESFLOW." where relations like '".$memberInfo['relations']."_%' and flow_time_str='{$monthStr}'";
			$this->db->query($sql);
			$teamSales = $this->db->fetchField('total');
		}
		return array('self_sales'=>$selfSales,'group_sales'=>$teamSales);
	}
	
	/**
	 * 获取返利用户详细信息
	 * @param unknown $memberId
	 */
	function get_tarento_detail($memberId){
		$res = array();
		if($memberId){
			$sql = "select a.*,b.name,b.qq,b.weixin,b.mobile from ".TARENTO." AS a left join ".MEMBER." AS b ON a.member_id=b.userid where a.member_id={$memberId}";
			$this->db->query($sql);
			$res = $this->db->fetchRow();
			if(!empty($res)){
				//团队人数
				$res['member_num'] = $this->get_tarento_group_total_num($memberId);
				//获取合伙人及他的团队本月销售额
				$sales = $this->get_tarento_current_month_sales($memberId);
				$res = array_merge($res,$sales);
			}
		}
		
		return $res;
	}
	
	/**
	 * 获取用户返利结算记录信息
	 * @param unknown $memberId
	 */
	function get_tarento_rebate_records($memberId){
		$arr = array();
		if($memberId>0){
			$sql = "select * from ".TARENTOSALESFLOW." where member_id={$memberId} ";
			$this->db->query($sql);
			$arr = $this->db->getRows();
			if(!empty($arr)){
				foreach ($arr as $k=>$v)
				{
					$salesInfo = $this->get_tarento_current_month_sales($memberId,$v['flow_time_str']);
					$arr[$k]['group_sales'] = $salesInfo['group_sales'];
					$arr[$k]['formart_time'] = substr($v['flow_time_str'], 0, 4)."年".substr($v['flow_time_str'], 4)."月";
				}
			}
		}
		
		return $arr;
	}
	
	/**
	 * 结算返利
	 * @param unknown $monthStr 如201509
	 */
	function settle_last_month_rebate($monthStr=''){
		if($monthStr=='' || $monthStr>=date('Ym')){//不传或传入当前月或比当前月大的值默认为上月
			$monthStr = date('Ym',strtotime('-1 month'));
		}
		
		/**先把应该结算但结算表没有数据的用户初始化***/
		$re = $this->preparation_for_settlement($monthStr);
		/*****/
		
		$sql = "select count(*) as total from ".TARENTOSALESFLOW." where flow_time_str='{$monthStr}' and status=0";
		$this->db->query($sql);
		$total = $this->db->fetchField('total');
		if(!($total>0)){
			return array('code'=>1,'msg'=>$monthStr.'已全部结算完成，无需再结算','result'=>array());
		}
		//普通用户
		$fail_general_member = array();
// 		$sql = "SELECT a.member_id,b.lowest_rate from ".TARENTOSALESFLOW." AS a left join ".TARENTO." as b on a.member_id=b.member_id WHERE a.relations='' and a.flow_time_str='{$monthStr}' and a.status=0";
// 		$this->db->query($sql);
// 		$n_member = $this->db->getRows();
// 		foreach ($n_member as $nv)
// 		{
// 			$f_mid = $this->settle_general_member_rebate($nv['member_id'],$nv['lowest_rate'],$monthStr);
// 			if($f_mid>0){//失败写入
// 				$fail_general_member[] = $f_mid;
// 			}
// 		}
		//合伙人
		$fail_tarento = array();
		$sql = "SELECT a.member_id,a.`level`,b.lowest_rate from ".TARENTOSALESFLOW." AS a left join ".TARENTO." as b on a.member_id=b.member_id WHERE a.relations!='' and a.flow_time_str='{$monthStr}' and a.status=0 ORDER BY a.`level` DESC";
		$this->db->query($sql);
		$t_member = $this->db->getRows();
		foreach ($t_member as $tv)
		{
			$f_tid = $this->settle_tarento_rebate($tv['member_id'],$tv['lowest_rate'],$monthStr);
			if($f_tid>0){//失败写入
				$fail_tarento[] = $f_tid;
			}
		}
		
		return array('code'=>0,'msg'=>'success','result'=>array('fail_general_member'=>$fail_general_member,'fail_tarento'=>$fail_tarento));
	}
	
	/**
	 * 结算前确认有结算金额的用户在结算表内有当月的记录
	 * @param string $monthStr 如201509
	 */
	public function preparation_for_settlement($monthStr)
	{
		$sql = "select relations from ".TARENTOSALESFLOW." where relations!='' and flow_time_str='{$monthStr}' and status=0 ";
		$this->db->query($sql);
		$arr = $this->db->getRows();
		if(!empty($arr)){
			$ids = "";
			foreach ($arr as $val)
			{
				$ids .= $val['relations'];
			}
			if(!empty($ids))
			{
				$idArr = explode(',', trim($ids,','));
				$idArr = array_unique($idArr);
				foreach ($idArr as $mid)
				{
				    if($mid){
    					$sql = "select id from ".TARENTOSALESFLOW." where member_id={$mid} and flow_time_str='{$monthStr}'";
    					$this->db->query($sql);
    					$m_s_id = $this->db->fetchField('id');
    					if(!$m_s_id){
    						$sql = "SELECT relations FROM ".TARENTOSALESFLOW." where FIND_IN_SET({$mid},`relations`) and flow_time_str='{$monthStr}' ORDER BY `level` LIMIT 1";
    						$this->db->query($sql);
    						$memberInfo = $this->db->fetchRow();
    						if(!empty($memberInfo)){
    						    //处理成该用户正确的关系和层级
    						    $relations = strstr($memberInfo['relations'], ','.$mid.',',true).$mid.',';
    						    $level = substr_count($relations, ',');
    						    
    							$sql = "insert into ".TARENTOSALESFLOW." (`member_id`,`relations`,`level`,`flow_time_str`) values('{$mid}','{$relations}','{$level}','{$monthStr}')";
    							$this->db->query($sql);
    						}
    					}
				    }
				}
			}
		}
		
		return true;
	}
	
	/**
	 * 结算一个合伙人用户
	 * @param unknown $memberId
	 * @param number $rate
	 * @param string $monthStr 如201509
	 */
	function settle_tarento_rebate($memberId,$rate=0,$monthStr='')
	{
		//获取当月销售额和团队总销售额
		$salesInfo = $this->get_tarento_current_month_sales($memberId,$monthStr);
		//获取团队结算总金额
		$group_back_price = $this->get_current_month_settlement($memberId,$monthStr);
		
		//计算包括本人总结算金额
// 		$allSales = $salesInfo['self_sales'] + $salesInfo['group_sales'];
		$allSales = $salesInfo['self_sales'];
		$real_rate = $this->get_rebate_rate($allSales);
		$rate = $rate>$real_rate?$rate:$real_rate;
		$allBackPrice = $allSales*$rate;
		
		//获取额外返利金额
// 		$extraPrice = $this->get_tarento_extra_rebate($memberId,$monthStr);
		
		//合伙人本人实得结算金额
// 		$self_back_price = $allBackPrice - $group_back_price + $extraPrice;
		$self_back_price = $allBackPrice;

		//更新结算数据
		$sql = "update ".TARENTOSALESFLOW." set self_back_price='{$self_back_price}',group_back_price='{$group_back_price}',status=1 where member_id={$memberId}  and flow_time_str='{$monthStr}' and status=0";
		$this->db->query($sql);
		if($self_back_price>0){
    		//更新账户余额,写入日志
    		$this->change_member_account($memberId,$self_back_price,'SETTLE_TARENTO_REBATE','合伙人返利结算'.$monthStr);
		}
		
		return 0;//合伙人暂时没判断是否有失败
	}
	
	/**
	 * 获取合伙人额外返利金额（直系下级做到最高档，一个多返3%）
	 * @param unknown $memberId
	 * @param string $monthStr
	 */
	function get_tarento_extra_rebate($memberId,$monthStr=''){
		$money = 0;
		$sql = "select relations,level from ".TARENTOSALESFLOW." where member_id={$memberId} and flow_time_str='{$monthStr}'";
		$this->db->query($sql);
		$memberInfo = $this->db->fetchRow();
		if(!empty($memberInfo) && $memberInfo['relations']){
			//查找最高档金额
			$sql = "select max(price_low) as price_low,max(lowest_rate) as lowest_rate from ".TARENTOBACKRATE." limit 1";
			$this->db->query($sql);
			$rateInfo = $this->db->fetchRow();
			//查找该合伙人直系下级超过最高档的销售信息
			$nextLevel = $memberInfo['level']+1;
			$sql = "select member_id from ".TARENTOSALESFLOW." where relations like '".$memberInfo['relations']."_%' and flow_time_str='{$monthStr}' and level='{$nextLevel}'";
			$this->db->query($sql);
			$memberList = $this->db->getRows();
			if(!empty($memberList)){
				$n = 0;//达到最高档的人数
				$high = array();//单个达到最高档团队的销售额集合
				$restTotal = 0;//单个未达到最高档团队销售额总和
				foreach ($memberList as $v)
				{
					$salesInfo = array();
					$allSales = 0;
					//获取当月销售额和团队总销售额
					$salesInfo = $this->get_tarento_current_month_sales($v['member_id'],$monthStr);
					//计算包括本人总结算金额
					$allSales = $salesInfo['self_sales'] + $salesInfo['group_sales'];
					if($allSales>=$rateInfo['price_low']){//达到最高档放入数组
						$high[] = array('sales'=>$allSales*$this->extra_rate);
						$n++;
					}else{//未达到累加
						$restTotal += $allSales;
					}
				}
				
				if($n>0){
					/***改为给合伙人加积分****/
					$sql = "update ".TARENTO." set extra_point=extra_point+{$n} where member_id={$memberId}";
					$this->db->query($sql);
					/***达到最高档加1积分****/
				}
// 				if($restTotal>=$rateInfo['price_low']){
// 					$n++;
// 				}
				
				//对达到最高档的销售额进行由高到低排序
// 				$high = arraySortByField($high,'sales','desc');
// 				if($n>1){//达到最高档的超过一个返额外金额
// 					for($i=0;$i<$n;$i++)
// 					{
// 						$money += $high[$i]['sales'];
// 					}
// 				}
			}
		}
		
		return $money;
	}
	
	/**
	 * 获取某合伙人当月团队结算总金额
	 * @param unknown $memberId
	 * @param string $monthStr 如201509
	 */
	function get_current_month_settlement($memberId,$monthStr='')
	{
		$group_back_price = 0;
		$sql = "select relations from ".TARENTOSALESFLOW." where member_id={$memberId} and flow_time_str='{$monthStr}'";
		$this->db->query($sql);
		$memberInfo = $this->db->fetchRow();
		if(!empty($memberInfo) && $memberInfo['relations']){
			$sql = "select sum(self_back_price) as total from ".TARENTOSALESFLOW." where relations like '".$memberInfo['relations']."_%' and flow_time_str='{$monthStr}' and status=1";
			$this->db->query($sql);
			$group_back_price = $this->db->fetchField('total');
		}
		return $group_back_price;
	}
	
	/**
	 * 结算一个普通用户
	 * @param unknown $memberId
	 * @param unknown $rate
	 * @param unknown $monthStr 如201509
	 */
	function settle_general_member_rebate($memberId,$rate=0,$monthStr='')
	{
		$back_price = 0;
		$sql = "select self_sales from ".TARENTOSALESFLOW." where member_id={$memberId} and flow_time_str='{$monthStr}' and status=0";
		$this->db->query($sql);
		$mem = $this->db->fetchRow();
		if(!empty($mem)){
			$real_rate = $this->get_rebate_rate($mem['self_sales']);
			if(!($rate>$real_rate)){
				$rate = $real_rate;
			}
			$back_price = $mem['self_sales']*$rate;
			
			//更新
			$sql = "update ".TARENTOSALESFLOW." set self_back_price='{$back_price}',status=1 where member_id={$memberId} and flow_time_str='{$monthStr}' and status=0";
			$this->db->query($sql);
			//更新余额
			$this->change_member_account($memberId,$back_price,'SETTLE_REBATE','返利结算'.$monthStr);
			return 0;//成功
		}
		return $memberId;//失败返回用户ID
	}
	
	/**
	 * 修改用户账户余额
	 * @param unknown $memberId
	 * @param number $price
	 * @param string $type_code 类型代码
	 * @param string $desc 描述
	 * @param string $operationStr 操作描述
	 * @param string $relationMId 相关用户ID
	 * @param string $isSelf 触发点是否是自己（推送消息）
	 */
	function change_member_account($memberId,$price=0,$type_code,$desc='',$operationStr='',$relationMId,$isSelf=false)
	{
	    //微信推送消息模板map
	    $typeArr = [
	        'PIN_TUAN'=>'pinTuanSuccess'
	    ];
		if($memberId>0){
		    $operationStr = $operationStr ? $operationStr : $_SESSION['ADMIN_USER'];
			//更新余额
			$sql = "update ".TARENTO." set account=account+({$price}) where member_id={$memberId}";
			$this->db->query($sql);
			//写入变更日志
			$sql = "insert into ".CASHFLOW."(member_id,price,type_code,description,extension) values ('$memberId','$price','$type_code','$desc','$operationStr')";
			$this->db->query($sql);
			
			//推送消息
			if (isset($typeArr[$type_code])) {
			    $nickName = "";
			    if (!$isSelf && $relationMId>0) {
    			    $sql = "select name from ".MEMBER." where userid={$relationMId}";
			        $this->db->query($sql);
			        $nickName = $this->db->fetchField('name');
			    }
			    //给店主推送消息
			    $replaceArr = [
			        'subject'=>[
			            '{{titlePre}}'=> $isSelf ? '您' : '您的商圈消费者',
			            '{{userName}}'=> $isSelf ? '' : '('.$nickName.')'
			        ]
			    ];
			    
			    $param = [
			        'memberId'=>$memberId,
			        'keyword1'=>$desc,
			        'keyword2'=>date('Y-m-d H:i:s'),
			        'keyword3'=>$this->config['money'].' '.$price,
			        'url'=>'http://wx.52ywy.com/?shop='.$memberId.'#&shop/index'
			    ];
			    include_once($this->config["webroot"]."/lib/Helper.php");
			    Helper::pushMessage($typeArr[$type_code], $replaceArr, $param);
			}
			
			return true;
		}
		return false;
	}
	
	/**
	 * 获取返利比例系数
	 * @param unknown $price 销售额
	 */
	function get_rebate_rate($price){
		$rate = 0;
		$sql = "select lowest_rate from ".TARENTOBACKRATE." where price_low<='{$price}' and price_high>='{$price}' limit 1";
		$this->db->query($sql);
		$lrate = $this->db->fetchField('lowest_rate');
		if($lrate>0){
			$rate = $lrate;
		}
		
		return $rate;
	}
	
	/**
	 * 构建用户邀请码
	 *
	 * @param unknown $userId
	 */
	public function buildInviteCode($userId)
	{
	        // TODO:暂时随机生成
        $codeArr = array();
        for ($i = 0; $i < 4; $i ++) {
            while (true) {
                $ascii = mt_rand(65, 90);
                if ($ascii != 79 && $ascii != 73) {
                    // 排除O字母和I
                    break;
                }
            }
            $codeArr[] = chr($ascii);
        }
        $code = implode('', $codeArr);
        
        //不开放只有2个字母和ABCD号
        $isOk = false;
        $countArr = array_count_values($codeArr);
        if (count($countArr)<=2 || $code == 'ABCD') {
            // 踩到靓号了，则递归重新生成
            return $this->buildInviteCode($userId);
        }
		$sql = "select id from ".TARENTO." where invite_code='{$code}' limit 1";
		$this->db->query($sql);
		$existsData = $this->db->fetchRow();
		if (! empty($existsData)) {
			// 重复了，则递归生成
			return $this->buildInviteCode($userId);
		}
		return $code;
	}
	
	/**
	 * 更新月销售额
	 * @param unknown $order_id
	 */
	public function updateUserSales($order_id){
		$sql = "select * from ".ORDERREC." where order_id={$order_id}";
		$this->db->query($sql);
		$orderInfo = $this->db->fetchRow();
		$userId = $orderInfo['rec_member_id'];

		if(!empty($orderInfo)){
			$flow_time_str = date('Ym',$orderInfo['order_time']);
			//查看结算表，如果本月有记录则更新月销售额字段，没有则新增
			$field = "`id`";
			$cond = "member_id={$userId} and flow_time_str='".$flow_time_str."' and status=0";
			$sql = "select {$field} from ".TARENTOSALESFLOW." where {$cond}";
			$this->db->query($sql);
			$salesFlow = $this->db->fetchRow();
			
			if(!empty($salesFlow) && $salesFlow['id']>0){//有则更新
				$sql = "update ".TARENTOSALESFLOW." set self_sales=self_sales+".$orderInfo['back_total_price']." where id={$salesFlow['id']}";
				$this->db->query($sql);
			}else{//无则新增
				//查找用户relations字段
				$sql = "select relations,level from ".TARENTO." where member_id={$userId}";
				$this->db->query($sql);
				$tarentoRelations = $this->db->fetchRow();
				
				$sql = "insert into ".TARENTOSALESFLOW." (`member_id`,`self_sales`,`relations`,`level`,`flow_time_str`) values ('{$userId}','{$orderInfo['back_total_price']}','{$tarentoRelations['relations']}','{$tarentoRelations['level']}','{$flow_time_str}')";
				$this->db->query($sql);
			}
			return true;
		}
		return false;
	}
}
?>
